/**
 * 用户服务实例的模型
 * Created by macos on 14-10-16.
 */

module.exports = {

  types: {
    description: function (value) {
      return true;
    }
  },

  attributes: {
    userId: {
      type: 'string',
      required: true,
      unique: true,
      description: '用户ID'
    },
    username: {
      type: 'string',
      required: true,
      description: '用户名'
    },
    services: {
      type: 'array',
      required: true,
      description: '服务名称'
    }
  },

  beforeValidate: function (values, next) {

    if (!_.has(values, 'service')) {
      return next('\''+ values.service + '\' is not input!');
    }

    MessageService.findOne({name: values.service})
      .exec(function (err, result) {
        if (err) {
          sails.log.error(err);
          return next(err);
        } else {
          if (_.has(result, 'id')) {
            delete values.service;
            next();
          } else {

            err = new Error();
            err.message = '\''+ values.service + '\' is not exist!';
            err.status = 404;

            return next(err);
          }
        }
      });
  }

}
